package com.linran.utils.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.platform.commons.util.StringUtils;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 年月日时分秒   生成logid的机器IP（12位）   6位随机串（建议前3位用毫秒数，后3位用16进制随机数）
 * 20170111104055 010006131078 058EAC
 */
@Slf4j
public class LogIdUtil {

    public static String generateLogId() {
        LocalDateTime now = LocalDateTime.now();
        String localDateTimeStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String ip = get12Ip();
        String milliseconds = now.format(DateTimeFormatter.ofPattern("SSS"));
        String randomHex = RandomStringUtils.random(3, 'A', 'B', 'C', 'D', 'E', 'F');
        return localDateTimeStr + ip + milliseconds + randomHex;
    }

    private static String get12Ip() {
        String hostAddress = getHostAddress();
        return convert12Ip(hostAddress);
    }

    private static String getHostAddress() {
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
            return addr.getHostAddress();
        } catch (UnknownHostException e) {
            log.error("[获取本机ip] 异常", e);
        }
        return null;
    }

    private static String convert12Ip(String hostAddress) {
        if (StringUtils.isNotBlank(hostAddress) && hostAddress.contains(".")) {
            StringBuilder sb = new StringBuilder();
            String[] split = hostAddress.split("\\.");
            for (String item : split) {
                sb.append(String.format("%03d", Integer.parseInt(item)));
            }
            return sb.toString();
        }
        //默认12位0
        return "000000000000";
    }
}
